import HttpConnection from "@/util/HttpConnection";

export default {
  data() {
    return {
      curPage: 1,
      limit: 10,
      total: 0,
      query: {},
      formInfo: {},
      tableData: null,
      dialogTitle: 0,
      dialogVisible: false
    };
  },
  methods: {
    queryData() {
      let that = this;
      HttpConnection.get(that.queryUrl, {
        params: that.getQueryParame()
      }).then(function (response) {
        that.tableData = response.data;
        that.total = response.count;
      }).catch(function (error) {
        that.tableData = null;
        that.total = 0;
        that.$message({
          type: "error",
          message: error.msg
        });
      });
    },
    getQueryParame() {
      return {
        current: this.curPage,
        size: this.limit,
        ...this.query
      };
    },
    toQuery() {
      this.curPage = 1;
      this.queryData();
    },
    resetQuery() {
      this.curPage = 1;
      this.query = {};
      this.queryData();
    },
    refreshQuery() {
      this.queryData();
    },
    handleSizeChange(val) {
      this.limit = val;
      this.queryData();
    },
    handleCurrentChange(val) {
      this.curPage = val;
      this.queryData();
    },
    handleAdd() {
      this.dialogVisible = true;
      this.dialogTitle = 0;
    },
    handleDelete(index, row) {
      let that = this;
      that.$confirm("此操作将删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      }).then(() => {
        HttpConnection.post(that.deleteUrl, {
          "ids": [row.id]
        }).then(function (response) {
          that.queryData();
          that.$message({
            type: "success",
            message: "删除成功!"
          });
        }).catch(function (error) {
          that.$message({
            type: "error",
            message: error.msg
          });
        });
      }).catch(() => {
        that.$message({
          type: "info",
          message: "已取消删除"
        });
      });
    },
    submitForm(formInfo) {
      let that = this;
      this.$refs[formInfo].validate((valid) => {
        if (valid) {
          let _apiTemp = "";
          if (that.dialogTitle === 0) {
            _apiTemp = that.addUrl;
          } else if (that.dialogTitle === 1) {
            _apiTemp = that.editUrl;
          }
          HttpConnection.post(_apiTemp, that.formInfo).then(function (response) {
            that.dialogVisible = false;
            that.$refs[formInfo].resetFields();
            that.queryData();
            that.$message({
              type: "success",
              message: "操作成功"
            });
          });
        } else {
          return false;
        }
      });
    },
    resetForm(formInfo) { // 新增 编辑 取消
      this.dialogVisible = false;
      this.$refs[formInfo].resetFields();
      this.formInfo = {};
    }
  }
};
